package usgs.bip.swap.ctl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;


import javax.servlet.http.*;

import sun.net.www.http.HttpClient;
import usgs.bip.swap.process.MasterListDAO;
import usgs.bip.swap.view.StateListHelper;

@SuppressWarnings("serial")
public class DataServlet extends HttpServlet {
	private MasterListDAO msList;
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		String state = req.getParameter("state");
		String type = req.getParameter("type");
		String json_file = req.getParameter("json_file");
		String output = "{ \"aaData\": [] }";
		String fileNamePrefix = getServletConfig().getInitParameter("qaqcFileBaseURL");
		String omissionFileNamePrefix = getServletConfig().getInitParameter("omissionFileBaseURL");
		String masterSpeciesListURL = fileNamePrefix + "MasterSGCN_Species_QAQC_List.txt";
		String fileName = fileNamePrefix;
		
		//HttpSession session = req.getSession(true);
		msList = new MasterListDAO(masterSpeciesListURL);
		/*
		if (msList == null) {
			msList = new MasterListDAO(masterSpeciesListURL);
			session.setAttribute("masterList", msList);
		} else {
			 msList = (MasterListDAO)session.getAttribute("masterList");		    
		}
		*/
		if(state != null && type != null){
			
			StateListHelper helper = new StateListHelper();
			String abbr = helper.getStateAbbreviation(state);
			
			fileName += abbr + "SGCN_Species_QAQC_List.txt";
					
			if(type.contains("splist")){
				output = this.getSpeciesListJSON(fileName);
			}
			else if(type.contains("changelist")){
				output = this.getChangedListJSON(fileName);
			}
			else if(type.contains("omissionlist")){
				fileName = omissionFileNamePrefix +  abbr + "_Natl_List_Omission.txt";
				output = this.getOmissionListJSON(fileName);
			}
		}
		else if((type != null && type.equalsIgnoreCase("json")) && json_file != null){
			//String jsonFile = jsonFileNamePrefix + file;
			//output = this.getRemoteJSONFile(jsonFile);
			fileName = fileNamePrefix + "MasterSGCN_Species_QAQC_List.txt";
			output = this.getRemoteJSONFile(fileName, json_file);
			
		}
        resp.setContentType("text/plain");
        resp.getWriter().println(output);
		 
	}

	private String getRemoteJSONFile(String remoteJSONFile, String jsonFileType) {

		String output = ""; 
		
		try {
			if(jsonFileType.equalsIgnoreCase("default")){
				output = msList.getDefaultJSON();
			}
			else if(jsonFileType.equalsIgnoreCase("state2taxa")){
				output = msList.getState2TaxaJSON();
			}
			else if(jsonFileType.equalsIgnoreCase("taxa2state")){
				output = msList.getTaxa2StateJSON();
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
	
		return output;
		
	}



	private String getSpeciesListJSON(String fileName) {		

		String output = "{ \"aaData\": [] }"; 
		String str = "";
		 
		
		URL summaryURL;
		
		try {
			
			summaryURL = new URL(fileName);
		
			BufferedReader data = new BufferedReader(new InputStreamReader(summaryURL.openStream()));
	 
		  	BufferedReader reader = new BufferedReader(data);
			String line = "";
			
			String sName = "";
			String cName = "";
			String cNameStr = "";
			String taxa = "";
			String state = "";
			int stateCount = 0;
			ArrayList<String> strList = new ArrayList<String>();
			
			while ((line = reader.readLine()) != null) {
		
				line = line.replaceAll("<(.*?)>", "");
				line = line.replaceAll("/\\n+|\\r+|^\\s+|\\s+$/","");
				line = line.trim();
				String[] list = line.split("\\t");
				int ct =list.length;
				String w = "";
				String tag = "";
				
				if(ct > 3 && !line.contains("Scientific Name")){
					
					
					for(int i=0; i<ct; i++){
						
						w = list[i];
						
						switch (i){
							
							case 0:
								sName = w;
								
							case 1:
								cName = w;
								cNameStr = cName;
								if(cName.contains("'")){
									cNameStr = URLEncoder.encode(cName);
								}
								break;
								
							case 2:
								taxa = w;
								break;
								
							case 3:
								state = w;
								String[] sList = state.split(";");
								stateCount = sList.length;
								break;
							 								
							default:
								break;
	
						}
					}
					
					 
					tag = "\t[ \" <span style='color:blue;cursor:pointer;' onclick=\\\"showMap('" + sName + "', '" + cNameStr + "', '" + state + "');\\\">"
					+ "<img src='/style/map_icon.png' alt='view map'/></span>\", \"" 
					+ sName + "\", \"" + cName + "\", \"" + taxa + "\", \"" + state + "\", " + stateCount + "]";
					strList.add(tag);
					
					
				}

	 
			}
			int ct = strList.size();
			output = "{ \"iRecordsTotal\": " + ct + ",\n";
			output += " \"aaData\": [\n";
			for(int i=0; i<ct; i++){
				String tag = (String) strList.get(i);
				if(i < ct-1){
					str += tag + ",\n";
				}
				else {
					str += tag + "\n";
				}
			}
			
			output += str + "] }\n";
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return output;
		
	}
	

	private String getChangedListJSON(String fileName) {

		String output = "{ \"aaData\": [] }"; 
		String str = "";
		
		URL summaryURL;
		try {
			//output = "{ \"aaData\": [\n";
			summaryURL = new URL(fileName);
		
			BufferedReader data = new BufferedReader(new InputStreamReader(summaryURL.openStream()));
	 
		  	BufferedReader reader = new BufferedReader(data);
			String line = "";

			ArrayList<String> strList = new ArrayList<String>();
			
			while ((line = reader.readLine()) != null) {
		
				line = line.replaceAll("<(.*?)>", "");
				line = line.replaceAll("/\\n+|\\r+|^\\s+|\\s+$/","");
				line = line.trim();
				String[] list = line.split("\\t");
				int ct =list.length;
				
				String w = "";
				String tag = "";
				String sName = "";
				String cName = "";
				String change = "";				
				String origName = "";
				String changeStr = "";
				
				if(ct > 4 && !line.contains("Scientific Name")){
					
					
					for(int i=0; i<ct; i++){
						
						w = list[i];
						
						switch (i){
							
							case 0:
								sName = w;
								
							case 1:
								cName = w;
								break;
									
							case 3:
							break;
								
							case 4:
								change = w;
								origName = change.replaceAll("^(.*?)(\\[Original name:)(.*?)(\\])(.*?)$", "$3");
								changeStr =  change.replaceAll("^(.*?)(\\[Original name:)(.*?)(\\])(.*?)$", "$1");							 	
								break;						 
								
							default:
								break;
	
						}
					}

					tag =  "\t[ \"" + origName + "\",  \"" + sName + "\", \"" + cName + "\",   \"" + changeStr + "\" ]";
					strList.add(tag);
					
				}
			}
			
			int ct = strList.size();
			output = "{ \"iRecordsTotal\": " + ct + ",\n";
			output += " \"aaData\": [\n";
			for(int i=0; i<ct; i++){
				String tag = (String) strList.get(i);
				if(i < ct-1){
					str += tag + ",\n";
				}
				else {
					str += tag + "\n";
				}
			}
			
			output += str + "] }\n";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return output;
		
	}
	
	private String getOmissionListJSON(String fileName) {

		String output = "{ \"aaData\": [] }"; 
		String str = "";
		
		URL summaryURL;
		try {
			output = "{ \"aaData\": [\n";
			summaryURL = new URL(fileName);
		
			BufferedReader data = new BufferedReader(new InputStreamReader(summaryURL.openStream()));
	 
		  	BufferedReader reader = new BufferedReader(data);
			String line = "";

			ArrayList<String> strList = new ArrayList<String>();
			
			while ((line = reader.readLine()) != null) {
		
				line = line.replaceAll("<(.*?)>", "");
				line = line.replaceAll("/\\n+|\\r+|^\\s+|\\s+$/","");
				line = line.trim();
				String[] list = line.split("\\t");
				int ct =list.length;
				
				String w = "";
				String tag = "";
				String sName = "";
				String cName = "";
				String taxa = "";				
				String omissionStr = "";
				 
				if(ct > 3 && !line.contains("Scientific Name")){
					
					
					for(int i=0; i<ct; i++){
						
						w = list[i];
						
						switch (i){
							
							case 0:
								sName = w;
								
							case 1:
								cName = w;
								break;
									
							case 2:
								taxa = w;
							break;
								
							case 3:
								omissionStr = w;
						 
								break;						 
								
							default:
								break;
	
						}
					}

					tag =  "\t[ \"" + sName + "\",  \"" + cName + "\", \"" + taxa + "\",   \"" + omissionStr + "\" ]";
					strList.add(tag);
					
				}
			}
			
			int ct = strList.size();
			for(int i=0; i<ct; i++){
				String tag = (String) strList.get(i);
				if(i < ct-1){
					str += tag + ",\n";
				}
				else {
					str += tag + "\n";
				}
			}
			
			output += str + "] }\n";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return output;
		
	}
	
}
